﻿using Castle.Core;
using Castle.Core.Logging;
using Castle.MicroKernel;
using Castle.MicroKernel.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Inovout
{
    public class LoggerResolver : ISubDependencyResolver
    {
        private readonly IExtendedLoggerFactory extendedLoggerFactory;
        private readonly ILoggerFactory loggerFactory;
        private readonly string logName;

        public LoggerResolver(ILoggerFactory loggerFactory)
        {
            if (loggerFactory == null)
            {
                throw new ArgumentNullException("loggerFactory");
            }

            this.loggerFactory = loggerFactory;
        }

        public LoggerResolver(IExtendedLoggerFactory extendedLoggerFactory)
        {
            if (extendedLoggerFactory == null)
            {
                throw new ArgumentNullException("extendedLoggerFactory");
            }

            this.extendedLoggerFactory = extendedLoggerFactory;
        }

        public LoggerResolver(ILoggerFactory loggerFactory, string name)
            : this(loggerFactory)
        {
            logName = name;
        }

        public LoggerResolver(IExtendedLoggerFactory extendedLoggerFactory, string name)
            : this(extendedLoggerFactory)
        {
            logName = name;
        }

        public bool CanResolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency)
        {
            return dependency.TargetType == typeof(ILogger) || dependency.TargetType == typeof(IExtendedLogger);
        }

        public object Resolve(CreationContext context, ISubDependencyResolver parentResolver, ComponentModel model, DependencyModel dependency)
        {
            if (extendedLoggerFactory != null)
            {
                return string.IsNullOrEmpty(logName)
                    ? extendedLoggerFactory.Create(model.Implementation)
                    : extendedLoggerFactory.Create(logName).CreateChildLogger(model.Implementation.FullName);
            }

            return string.IsNullOrEmpty(logName)
               ? loggerFactory.Create(model.Implementation)
               : loggerFactory.Create(logName).CreateChildLogger(model.Implementation.FullName);
        }
    }

}
